package com.fwh.web.controller;

import com.qq.connect.utils.RandomStatusGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 微信网页登录功能
 *
 * @Author: fwh
 * @date 2019/4/12&& 9:27
 */
@Slf4j
@Controller
@RequestMapping("/weChatController")
public class WeChatController {
//    @Value("${weChatAppId}")
//    private String weChatAppId;
    /**
     * 微信登录功能--主要为了获取code值
     *
     * @param request
     * @param response
     */
    @GetMapping("/login")
    public void login(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        String state = RandomStatusGenerator.getUniqueState();
        String appID = "wxbdc5610cc59c1631";//一号店的
        String redirectUrl = "192.168.1.197/WeChatController/auth";//回调地址要与微信上申请的一致.否则调用不通过.
        String scope = "snsapi_login";
        String requestUrl = "https://open.weixin.qq.com/connect/qrconnect?appid=" + appID + "&redirect_uri=" + redirectUrl + "&response_type=code&scope=" + scope + "&state=" + state + "#wechat_redirect";
        log.info("请求微信地址为:{}", requestUrl);
        try {
            response.sendRedirect(requestUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 微信授权认证登录--通过获取的code再取token和openid(唯一值)
     *
     * @param
     * @return void
     * @author:fwh [2019/4/12 && 10:35]
     */
    @GetMapping("/auth")
    public void auth(@RequestParam("code") String code) {
        log.info("进入auth方法");
        log.info("code={}", code);
//        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx78bbd7339eb062c9&secret=d676fa24057096f53067d689c84daa53&code=" + code + "&grant_type=authorization_code";
        String url = "https://open.weixin.qq.com/connect/qrconnect?appid=wxbdc5610cc59c1631&redirect_uri=https%3A%2F%2Fpassport.yhd.com%2Fwechat%2Fcallback.do&response_type=code&scope=snsapi_login&state=3d6be0a4035d839573b04816624a415e#wechat_redirect";
        //https://passport.yhd.com/passport/login_input.do?returnUrl=http%3A%2F%2Fwww.yhd.com
//        https://open.weixin.qq.com/connect/qrconnect?appid=wxbdc5610cc59c1631&redirect_uri=https%3A%2F%2Fpassport.yhd.com%2Fwechat%2Fcallback.do&response_type=code&scope=snsapi_login&state=4735931168977c37f6494bcd00e01e47#wechat_redirect
        // 这里的getForObject()是发送一个HTTP GET请求，返回的请求体将映射为一个对象
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);
        log.info("response={}", response);
    }
}
